<?php
/**
 * Created by PhpStorm.
 * userValidate: hms
 * Date: 2018/8/7
 * Time: 9:27
 */

namespace app\firm\controller;

use think\Controller;
use think\Config;
use redis\Redis;
use think\Request;
use think\Db;
use think\response\Download;
use app\firm\model\ProjectUser;
use app\firm\model\NewProject;
use app\firm\model\ApplicationForMoney;
use app\firm\model\Project;
use app\firm\model\ProjectBank;
use app\firm\model\MoneyReturn;
use app\firm\model\MoneyReturns;
use app\firm\model\Notice;
use app\firm\model\Order;
use app\firm\validate\projectValidate;
use expand\Yunst;
use expand\YunPay;

class Firmproject extends Common
{
    
    /*
     * 项目列表
     * @param Request $request
     * @param NewProject $newProject
     * @author cpy(1442435897@qq.com)
     * @return \think\response\Json
     */
    public function index(Request $request , NewProject $newProject) {
        $param = $request->param();
        $user_info = $request->firm_info;
        $pageNumber = $param['pageNumber'] ? $param['pageNumber'] : 1;
        $pageSize = $param['pageSize'] ? $param['pageSize'] : 10;
        $limit = ($pageNumber - 1) * $pageSize . ',' . $pageSize;
        $where['company_id'] = ['eq',$user_info['id']];
        if($param['project_name'])
            $where['project_name'] = ['like', '%'.$param['project_name'].'%'];
        if($param['status'])
            $where['status'] = ['eq', $param['status']];
        if($param['start_time'] && $param['end_time']){
            if($param['start_time']==$param['end_time']){
                $param['end_time']=$param['end_time']+86400;
            }
            $where['create_time'] = ['between time', [$param['start_time'],$param['end_time']]];
        }
        $res = $newProject->selectProjectInfo($where,$limit);
        $total = $newProject->selectInfo($where,'id');
        $owhere['company_id'] = ['eq',$user_info['id']];
        $owhere['status'] = ['eq', 1];
        $row1 = $newProject->selectInfo($owhere,'id');
        $owhere['status'] = ['eq', 2];
        $row2 = $newProject->selectInfo($owhere,'id');
        $owhere['status'] = ['eq', 3];
        $row3 = $newProject->selectInfo($owhere,'id');
        $result = Config::get('code.success');
        $result['data'] = $res;
        $result['total'] = count($total);
        $result['waitCheck'] = count($row1);
        $result['success'] = count($row2);
        $result['error'] = count($row3);
        return json($result);
    }
    
    /*
     * 文件上传
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return \think\response\Json
     */
    public function uploadFile(Request $request) {
        $user_info = $request->firm_info;
        $redis = Redis::instance();
        $file = request()->file('file');
        $res = upload($file, 'firmProject');
        $url = str_replace('\\','/',$res);
        if($url){
            $redis->set('user_url:' . $user_info['id'] , $url);
            $result = Config::get('code.success');
            $result['url'] = $url;
        }else{
            $result = Config::get('code.error');
        }
        return json($result);
    }
    
    /*
     * 添加项目
     * @param Request $request
     * @param NewProject $newProject
     * @param ProjectBank $projectBank
     * @author cpy(1442435897@qq.com)
     * @return \think\response\Json
     */
    public function addProject(Request $request , NewProject $newProject , ProjectBank $projectBank) {
        $param = $request->param();
        $redis = Redis::instance();
        $user_info = $request->firm_info;
        $validate = new projectValidate();
        if ($validate->check($param)) {
//            $where['id'] = ['eq',$param['bank_id']];
//            $where['pjtuser_id'] = ['eq',$user_info['id']];
//            $res = $projectBank->getBankInfo($where,'bank_num,bank_name');
//            if(empty($res)){
//                return json(Config::get('code.errorBankId'));
//            }
            $url = $redis->get('user_url:' . $user_info['id']);
            $param['company_id'] = $user_info['id'];
            $param['appendix'] = $url;
//            $param['settlement_bank_card'] = $res['bank_num'];
//            $param['settlement_bank_name'] = $res['bank_name'];
            if($newProject->save($param)){
                $result = Config::get('code.success');
            }else{
                $result = Config::get('code.error');
            }
        } else {
            $result['msg'] = $validate->getError();
            $result['status'] = 203;
        }
//        $where['pjtuser_id'] = $user_info['id'];
//        $data = $projectBank->selectBankInfo($where,'id,bank_num,bank_name');
//        $result['data'] = $data;
        return json($result);
    }
    
    /*
     * 文件下载
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return \think\response\Json
     */
    public function download(Request $request , NewProject $newProject)
    {
        $param = $request->param();
        $where['id'] = ['eq',$param['id']];
        $res= $newProject->getInfo($where,'appendix');
        $famlePath = $res['appendix'];
        $file_lj = str_replace("\\","/",ROOT_PATH.'public');
        $file_dir = $file_lj . '/' . 'uploads' . '/firmProject/' . "$famlePath";    // 下载文件存放目录
        // 检查文件是否存在
        if (! file_exists($file_dir) ) {
            $this->error('文件未找到');
        }else{
            // 打开文件
            $file1 = fopen($file_dir, "r");
            // 输入文件标签
            Header("Content-type: application/octet-stream");
            Header("Accept-Ranges: bytes");
            Header("Accept-Length:".filesize($file_dir));
            Header("Content-Disposition: attachment;filename=" . $file_dir);
            ob_clean();     // 重点！！！
            flush();        // 重点！！！！可以清除文件中多余的路径名以及解决乱码的问题：
            //输出文件内容
            //读取文件内容并直接输出到浏览器
            echo fread($file1, filesize($file_dir));
            fclose($file1);
            exit();
        }
    }
    
    /*
     * 项目详情
     * @param Request $request
     * @param NewProject $newProject
     * @param ProjectBank $projectBank
     * @author cpy(1442435897@qq.com)
     * @return \think\response\Json
     */
    public function projectDetail(Request $request, NewProject $newProject, ProjectBank $projectBank) {
        $param = $request->param();
        $user_info = $request->firm_info;
        $where['id'] = ['eq',$param['id']];
        $where['company_id'] = ['eq',$user_info['id']];
        $projectInfo = $newProject->getInfo($where,'id,project_name,target_code,platform,joint_venture,joint_investment,release_cycle,project_detail,bank_id,settlement_bank_card,appendix,status');
        $prefix = substr($projectInfo['settlement_bank_card'], 0, 4);
        $suffix = substr($projectInfo['settlement_bank_card'], -4, 4);
        $maskBankCardNo = $prefix . " **** **** **** " . $suffix;
        $projectInfo['settlement_bank_card'] = $maskBankCardNo;
        $result = Config::get('code.success');
        $result['data']['projectInfo'] = $projectInfo;
        return json($result);
    }

    /*
     * 修改项目
     * @param Request $request
     * @param NewProject $newProject
     * @param ProjectBank $projectBank
     * @author cpy(1442435897@qq.com)
     * @return \think\response\Json
     */
    public function editProject(Request $request, NewProject $newProject, ProjectBank $projectBank) {
        $param = $request->param();
        $user_info = $request->firm_info;
        $where['id'] = $param['id'];
        $where['company_id'] = $user_info['id'];
        $projectInfo = $newProject->getInfo($where, 'id,project_name,target_code,platform,joint_venture,joint_investment,release_cycle,project_detail,settlement_bank_card,appendix,status');
//        $prefix = substr($projectInfo['settlement_bank_card'], 0, 4);
//        $suffix = substr($projectInfo['settlement_bank_card'], -4, 4);
//        $maskBankCardNo = $prefix . " **** **** **** " . $suffix;
//        $projectInfo['settlement_bank_card'] = $maskBankCardNo;
        unset($param['id']);
        if ($param) {
            if ($projectInfo['id'] && $projectInfo['status'] != 2) {
                if($projectInfo['status'] == 3)
                    $param['status'] = 1;
                if ($newProject->save($param, ['id' => $projectInfo['id']])) {
                    $result = Config::get('code.success');
                } else {
                    $result = Config::get('code.error');
                }
            } else {
                $result['status'] = 203;
                $result['msg'] = '已通过项目无法修改！';
            }
        }
//        $bwhere['pjtuser_id'] = $user_info['id'];
//        $bankInfo = $projectBank->selectBankInfo($bwhere, 'id,bank_num,bank_name');
//        foreach ($bankInfo as $k => $val) {
//            $prefix = substr($val['bank_num'], 0, 4);
//            $suffix = substr($val['bank_num'], -4, 4);
//            $maskBankCardNo = $prefix . " **** **** **** " . $suffix;
//            $bankInfo[$k]['bank_num'] = $maskBankCardNo;
//        }
        $result = Config::get('code.success');
        $result['data']['projectInfo'] = $projectInfo;
//        $result['data']['bankInfo'] = $bankInfo;
        return json($result);
    }

    /*
     * 用款申请列表
     * @param Request $request
     * @param NewProject $newProject
     * @author cpy(1442435897@qq.com)
     * @return \think\response\Json
     */
    public function appList(Request $request, ApplicationForMoney $afMoney) {
        $user_info = $request->firm_info;
        $param = $request->param();
        if($param['project_name'])
            $where['b.project_name'] = ['like', '%'.$param['project_name'].'%'];
        if($param['type'])
            $where['a.status'] = ['eq', $param['type']];
        $where['company_id'] = ['eq', $user_info['id']];
        $res = $afMoney->selectJoinProject($where, 'a.*,b.id as project_id,b.project_name');
        $rwhere['company_id'] = ['eq', $user_info['id']];
        $total = $afMoney->selectInfo($rwhere,'id');
        $rwhere['status'] = ['eq', 1];
        $row1 = $afMoney->selectInfo($rwhere,'id');
        $rwhere['status'] = ['eq', 2];
        $row2 = $afMoney->selectInfo($rwhere,'id');
        $rwhere['status'] = ['eq', 3];
        $row3 = $afMoney->selectInfo($rwhere,'id');
        $result = Config::get('code.success');
        $result['data'] = $res;
        $result['total'] = count($total);
        $result['waitCheck'] = count($row1);
        $result['success'] = count($row2);
        $result['error'] = count($row3);
        return json($result);
    }

    /*
     * 发起用款申请
     * @param Request $request
     * @param ApplicationForMoney $afMoney
     * @author cpy(1442435897@qq.com)
     * @return \think\response\Json
     */
    public function startApp(Request $request , ApplicationForMoney $afMoney , Project $project , Notice $notice) {
        $user_info = $request->firm_info;
        $redis = Redis::instance();
        $param = $request->param();
        $code = $redis->get('app_code_' . $user_info['mobile']);
        if ($param) {
//            if ($code === $param['code']) {
                $where['initiator'] = ['eq',$user_info['id']];
                $where['id'] = ['eq',$param['project_id']];
                $info = $project->getInfo($where,'project_name');
                if($info){
                    if ($afMoney->save(['company_id' => $user_info['id'], 'project_id' => $param['project_id'], 'money' => $param['money']])) {
                        $data = [
                            'uid' => $user_info['id'],
                            'title' => '用款',
                            'content' => '您好,企业家,您于2019-02-22 12:23:12发起项目<'.$info['project_name'].'>的用款申请,我们将于3-7个工作日完成审核,如有疑问,欢迎致电400-605-9006',
                            'type' => 2
                        ];
                        $notice->save($data);
                        $result = Config::get('code.success');
                    } else {
                        $result = Config::get('code.error');
                    }
                }else{
                    $result = Config::get('code.notBeingProject');
                }
//            } else {
//                $result = Config::get('code.codeFail');
//            }
        }else{
            $where['initiator'] = ['eq',$user_info['id']];
            //$where['status'] = ['eq',3];
            $res = $project->selectProjectInfo($where,'id,project_name');
            $result = Config::get('code.success');
            $result['data'] = $res;
        }
        return json($result);
    }
    
    /*
     * 根据project_id获取申请余额
     * @param Request $request
     * @param ApplicationForMoney $afMoney
     * @author cpy(1442435897@qq.com)
     * @return \think\response\Json
     */
    public function getProjectMoney(Request $request , ApplicationForMoney $afMoney , Project $project) {
        $user_info = $request->firm_info;
        $param = $request->param();
        $where['id'] = ['eq',$param['project_id']];
        $info = $project->getInfo($where,'target_code');
        $awhere['company_id'] = ['eq',$user_info['id']];
        $awhere['project_id'] = ['eq',$param['project_id']];
        $awhere['status'] = ['<',3];
        $res = $afMoney->selectInfo($awhere,'sum(money)');
        $balance = $info['target_code'] - $res[0]['sum(money)'];
        $result = Config::get('code.success');
        $result['balance'] = $balance;
        return json($result);
    }
    
    /*
     * 获取用款申请验证码
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return \think\response\Json
     */
    public function getAppCode(Request $request) {
        $user_info = $request->firm_info;
        $res = redisCode($user_info['mobile'],'app_code_');
        if($res){
            $row = SmsToSend($user_info['mobile'],$res);
            if($row['code'] == 0){
                $result = Config::get('code.success');
            }else{
                $result = Config::get('code.error');
                $result['msg'] = $row['msg'];
            }
        }else{
            $result = Config::get('code.error');
        }
        return json($result);
    }
    
    /*
     * 项目回款列表
     * @param Request $request
     * @param MoneyReturn $moneyReturn
     * @author cpy(1442435897@qq.com)
     * @return \think\response\Json
     */
    public function payBackList(Request $request, MoneyReturn $moneyReturn) {
        $user_info = $request->firm_info;
        $param = $request->param();
        $pageNumber = $param['pageNumber'] ? $param['pageNumber'] : 1;
        $pageSize = $param['pageSize'] ? $param['pageSize'] : 10;
        $limit = ($pageNumber - 1) * $pageSize . ',' . $pageSize;
        $where['company_id'] = ['eq',$user_info['id']];
        if($param['status'])
            $where['a.status'] = ['eq',$param['status']];
        if($param['project_name'])
            $where['b.project_name'] = ['like', '%'.$param['project_name'].'%'];
        $res = $moneyReturn->selectLimitInfo($where,$limit,'a.*,b.id as project_id,b.project_name');
        $twhere['company_id'] = ['eq',$user_info['id']];
        $total = $moneyReturn->selectInfo($twhere,'id');
        $twhere['status'] = ['eq',1];
        $row1 = $moneyReturn->selectInfo($twhere,'id');
        $twhere['status'] = ['eq',2];
        $row2 = $moneyReturn->selectInfo($twhere,'id');
        $result = Config::get('code.success');
        $result['data'] = $res;
        $result['total'] = count($total);
        $result['waitPayBack'] = count($row1);
        $result['success'] = count($row2);
        return json($result);
    }
    
    /*
     * 项目回款详情
     * @param Request $request
     * @param MoneyReturn $moneyReturn
     * @author cpy(1442435897@qq.com)
     * @return \think\response\Json
     */
    public function payBackDetail(Request $request, MoneyReturn $moneyReturn) {
        $user_info = $request->firm_info;
        $param = $request->param();
        $where['company_id'] = ['eq',$user_info['id']];
        $where['a.id'] = ['eq',$param['return_id']];
        $res = $moneyReturn->getJoinInfo($where,'b.project_name,a.money,a.remarks');
        $result = Config::get('code.success');
        $result['data'] = $res;
        return json($result);
    }
    
    /*
     * 回款
     * @param Request $request
     * @param MoneyReturn $moneyReturn
     * @author cpy(1442435897@qq.com)
     * @return \think\response\Json
     */
    public function payBack(Request $request, MoneyReturn $moneyReturn, MoneyReturns $moneyReturns,ProjectUser $projectUser, Project $project, Yunst $YunClass, Order $orderModel) {
        $user_info = $request->firm_info;
        $redis = Redis::instance();
        $param = $request->param();
        $mwhere['id'] = ['eq', $param['return_id']];
        $mwhere['company_id'] = ['eq', $user_info['id']];
        $info = $moneyReturn->getInfo($mwhere);
        if (!$info)
            return json(Config::get('code.mistake'));
//        if ($info['money'] < Config::get('queue.lowestCash')) {
//            $result['status'] = 301;
//            $result['msg'] = '回款金额最低不得少于'.Config::get('queue.lowestCash').'元!';
//            return json($result);
//        }
        if ($user_info['money'] < $info['money'])
            return json(Config::get('code.overBalance'));
        if ($user_info['pay_password'] != sha1(md5($param['pay_password'] . $user_info['pay_salt'])))
            return json(Config::get('code.errorPayPwd'));
        
        $pwhere['id'] = ['eq', $info['project_id']];
        $pMoney = $project->getInfo($pwhere, 'target_code,basic_code');
//        $scale = sprintf("%.2f", $info['money'] / $pMoney['target_code']);
        $scale = sprintf("%.10f", $info['money'] / ($pMoney['target_code']-$pMoney['basic_code']));
        $where['a.project_id'] = ['eq', $info['project_id']];
        $where['a.status'] = ['eq',2];
        $res = $orderModel->selectJoinGroupInfo($where, 'uid', 'b.bizUserId,sum(a.money) as maxmoney');
        foreach ($res as $k => $v) {
            $data[] = [
                'bizUserId' => $v['bizUserId'],
                'amount' => sprintf("%.2f", $v['maxmoney'] * $scale) * 100,
            ];
        }
        
        $final = $YunClass->DanBiDaiShouCom($user_info['bizUserId'], $info, $data);
        file_put_contents(BASE_PATH.'log/'.date("Y-m-d H", time()).'pay_back.txt',json_encode($final,JSON_UNESCAPED_UNICODE).PHP_EOL,FILE_APPEND);
        if ($final['status'] != 'OK') {
            $result['status'] = 301;
            $result['msg'] = $final['message'];
            return json($result);
        }
        $signedValue = json_decode($final['signedValue'], true);
        $res = $moneyReturn->where('id', $param['return_id'])->update(['order_sn' => $signedValue['orderNo']]);
        $redis->set('user_return:' . $user_info['id'], $param['return_id']);
        $result = Config::get('code.success');
        return json($result);
    }
    
    /*
     * 回款确认页面
     * @param Request $request
     * @param MoneyReturn $moneyReturn
     * @author cpy(1442435897@qq.com)
     * @return \think\response\Json
     */
    public function payBackConfirm(Request $request, MoneyReturn $moneyReturn) {
        $user_info = $request->firm_info;
        $redis = Redis::instance();
        $return = $redis->get('user_return:' . $user_info['id']);
        $mwhere['id'] = ['eq', $return];
        $mwhere['company_id'] = ['eq', $user_info['id']];
        $info = $moneyReturn->getInfo($mwhere,'money,order_sn,create_time');
        if($info){
            $info['mobile'] = $user_info['mobile'];
            $result = Config::get('code.success');
            $result['data'] = $info;
        }else{
            $result = Config::get('code.error');
        }
        return json($result);
    }

    /*
     * 回款确认支付
     * @param Request $request
     * @param MoneyReturn $moneyReturn
     * @param ProjectUser $projectUser
     * @param Yunst $YunClass
     * @author cpy(1442435897@qq.com)
     * @return \think\response\Json
     */
    public function confirmPay(Request $request, ProjectUser $projectUser, MoneyReturn $moneyReturn, Yunst $YunClass) {
        $user_info = $request->firm_info;
        $redis = Redis::instance();
        $param = $request->param();
        
        $return = $redis->get('user_return:' . $user_info['id']);
        $mwhere['id'] = ['eq', $return];
        $mwhere['company_id'] = ['eq', $user_info['id']];
        $info = $moneyReturn->getInfo($mwhere);
        if ($user_info['money'] < $info['money'])
            return json(Config::get('code.overBalance'));
        $res = $YunClass->balancePay($user_info['bizUserId'], $info['order_no'], $param['code']);
        file_put_contents('confirmPay.txt',json_encode($res,JSON_UNESCAPED_UNICODE).PHP_EOL,FILE_APPEND);
        if ($res['status'] != 'OK') {
            $result['status'] = 301;
            $result['msg'] = $res['message'];
            return json($result);
        }
        Db::startTrans();
        try {
            $setMoney = $user_info['money'] - $info['money'];
            $row = $projectUser->where('id', $user_info['id'])->update(['money' => $setMoney]);
            $token = $redis->get('user:' . $user_info['id']);
            $user_info['money'] = $setMoney;
            $redis->hSet('firm_info', $token, json_encode($user_info));
            Db::commit();
            $result = Config::get('code.success');
        } catch (\Exception $e) {
            Db::rollback();
            return $e->getMessage();
            $result = Config::get('code.error');
        }
        return json($result);
    }

}